<template>
    <div class="container containerStudent">
        <!-- header -->
        <div class="header">
            <div class="header-box">
                <p class="header-title">学校名称:</p>
                <el-cascader
                    v-model="header.school_id"
                    :options="schoolList"
                    @change="getTableData(1)"
                    size="small"
                    clearable
                    :props="{
                        value: 'value',
                        label: 'label',
                        children: 'children'
                    }"
                />
            </div>
            <div class="header-box">
                <p class="header-title">掌大精英姓名:</p>
                <el-input
                    v-model="header.tel"
                    placeholder="请输入姓名"
                    suffix-icon="el-icon-search"
                    size="small"
                    clearable
                    class="search-ipt"
                    @change="getTableData(1)"
                    @keyup.native.enter="getTableData(1)"
                />
            </div>
            <div class="header-box">
                <p class="header-title">掌大精英搜索:</p>
                <el-input
                    v-model="header.keyword_pre_stuagent_student_id"
                    placeholder="用户ID或手机号"
                    suffix-icon="el-icon-search"
                    size="small"
                    clearable
                    class="search-ipt"
                    @change="getTableData(1)"
                    @keyup.native.enter="getTableData(1)"
                />
            </div>
            <div class="header-box">
                <p class="header-title">粉丝姓名:</p>
                <el-input
                    v-model="header.telFans"
                    placeholder="请输入姓名"
                    suffix-icon="el-icon-search"
                    size="small"
                    clearable
                    class="search-ipt"
                    @change="getTableData(1)"
                    @keyup.native.enter="getTableData(1)"
                />
            </div>
            <div class="header-box">
                <p class="header-title">粉丝搜索:</p>
                <el-input
                    v-model="header.keyword_student_id"
                    placeholder="用户ID或手机号"
                    suffix-icon="el-icon-search"
                    size="small"
                    clearable
                    class="search-ipt"
                    @change="getTableData(1)"
                    @keyup.native.enter="getTableData(1)"
                />
            </div>
            <div class="header-box">
                <p class="header-title">是否购买:</p>
                <el-select
                    v-model="header.purchase"
                    placeholder="请选择"
                    size="small"
                    @change="getTableData(1)"
                    clearable
                >
                    <el-option
                        v-for="item in header.purchaseList"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                    />
                </el-select>
            </div>
            <!-- <div class="header-box">
                <p class="header-title">选择时间:</p>
                <el-date-picker
                    v-model="header.date"
                    type="daterange"
                    size="small"
                    range-separator="至"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期"
                    @change="getTableData(1)"
                />
            </div> -->
            <div class="header-box">
                <el-button
                    type="primary"
                    size="small"
                    @click="fnFormReset()"
                >
                    重置
                </el-button>
            </div>
        </div>
        <!-- /header -->

        <!-- table -->
        <el-table
            :data="tableData"
            height="100%"
            style="width: 100%;"
            ref="goodsTable"
            border
            @select="fnSelect"
            @select-all="fnSelectAllTop"
            @selection-change="handleSelectionChange"
        >
            <el-table-column
                type="selection"
                width="40"
            />
            <el-table-column
                label="序号"
                width="100px"
                align="center"
                type="index"
                fixed="left"
            />
            <el-table-column
                prop="pre_stuagent_true_name"
                label="所属管培生"
                :width="160"
                show-overflow-tooltip
                :formatter="emptyFormatter"
            >
                <template slot-scope="scope">
                    <p>姓名:{{ scope.row.pre_stuagent_true_name }}</p>
                    <p>手机号:{{ scope.row.pre_stuagent_phone }}</p>
                    <p>Id:{{ scope.row.pre_stuagent_student_no }}</p>
                </template>
            </el-table-column>
            <el-table-column
                prop="true_name"
                label="粉丝姓名"
                show-overflow-tooltip
                :formatter="emptyFormatter"
            />
            <el-table-column
                prop="student_no"
                label="用户Id"
                :width="160"
                show-overflow-tooltip
                :formatter="emptyFormatter"
            />
            <el-table-column
                prop="phone"
                label="手机号"
                :width="120"
                show-overflow-tooltip
                :formatter="emptyFormatter"
            />
            <el-table-column
                prop="school_name"
                label="学校名称"
                show-overflow-tooltip
                :formatter="emptyFormatter"
            />
            <el-table-column
                prop="school_college_name"
                label="学院名称"
                show-overflow-tooltip
                :formatter="emptyFormatter"
            />
            <el-table-column
                prop="join_time"
                label="加入时间"
                show-overflow-tooltip
                :formatter="emptyFormatter"
            >
                <template slot-scope="scope">
                    {{ scope.row.join_time * 1000 | dateFormatter('yyyy/MM/dd HH:mm') }}
                </template>
            </el-table-column>
            <el-table-column
                prop="is_buy"
                label="是否购买"
                show-overflow-tooltip
                :formatter="emptyFormatter"
            >
                <template slot-scope="scope">
                    <span v-if="scope.row.is_buy == 1">是</span>
                    <span v-if="scope.row.is_buy == 0">否</span>
                </template>
            </el-table-column>
            <el-table-column
                prop="buy_num"
                label="购买次数"
                show-overflow-tooltip
                :formatter="emptyFormatter"
            />
            <el-table-column
                label="购买记录"
                show-overflow-tooltip
                :formatter="emptyFormatter"
            >
                <template slot-scope="scope">
                    <el-button
                        type="text"
                        :disabled="scope.row.buy_num == 0"
                        @click="fnGetbuyList(scope.row)"
                    >
                        查看
                    </el-button>
                </template>
            </el-table-column>
            <el-table-column
                prop="person_money"
                label="个人消费金额"
                show-overflow-tooltip
                :width="140"
                :formatter="emptyFormatter"
            >
                <template slot-scope="scope">
                    <span>{{ scope.row.person_money | setPrice }}元</span>
                </template>
            </el-table-column>
            <el-table-column
                prop="rebate"
                label="预估佣金"
                show-overflow-tooltip
                :formatter="emptyFormatter"
            >
                <template slot-scope="scope">
                    <span>{{ scope.row.rebate | setPrice }}元</span>
                </template>
            </el-table-column>
        </el-table>
        <!-- /table -->

        <!-- 查看购买记录 -->
        <el-dialog
            :visible.sync="DialogVisibleList"
            width="760px"
            class="seckillDialogVisible"
        >
            <el-table
                :data="tableDataReord"
                height="100%"
                style="width: 100%;"
                border
            >
                <el-table-column
                    label="序号"
                    type="index"
                    show-overflow-tooltip
                    :formatter="emptyFormatter"
                />
                <el-table-column
                    prop="create_time"
                    label="下单日期"
                    show-overflow-tooltip
                    :formatter="emptyFormatter"
                >
                    <template slot-scope="scope">
                        {{ scope.row.create_time * 1000 | dateFormatter('yyyy/MM/dd HH:mm') }}
                    </template>
                </el-table-column>
                <el-table-column
                    prop="aim_type"
                    label="商品类型"
                    show-overflow-tooltip
                >
                    <template slot-scope="scope">
                        {{ scope.row.aim_type | setAimtype }}
                    </template>
                </el-table-column>
                <el-table-column
                    prop="ori_money"
                    label="实付款"
                    show-overflow-tooltip
                >
                    <template slot-scope="scope">
                        {{ scope.row.ori_money }}
                    </template>
                </el-table-column>
                <el-table-column
                    prop="rebate_money"
                    label="产生佣金"
                    show-overflow-tooltip
                >
                    <template slot-scope="scope">
                        {{ scope.row.rebate_money }}
                    </template>
                </el-table-column>
                <el-table-column
                    prop="status"
                    label="订单状态"
                    show-overflow-tooltip
                >
                    <template slot-scope="scope">
                        {{ scope.row.status | setStatus }}
                    </template>
                </el-table-column>
                <el-table-column
                    label="操作"
                    show-overflow-tooltip
                >
                    <template slot-scope="scope">
                        <el-button
                            type="text"
                            @click="fnJumpShop(scope.row)"
                        >
                            查看
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
        </el-dialog>
        <!-- /查看购买记录 -->

        <!-- 分配弹窗 -->
        <el-dialog
            title="分配管培生"
            :visible.sync="dialogVisibleFp"
            width="580px"
            class="el-dialogFp"
            :close-on-click-modal="false"
        >
            <el-form
                :model="ruleForm"
                ref="ruleFormFp"
                class="demo-ruleForm"
                @submit.native.prevent
            >
                <el-form-item
                    label="搜索管培生手机号:"
                    label-width="140px"
                >
                    <el-input
                        v-model="ruleForm.phone"
                        size="small"
                        placeholder="请输入手机号"
                        type="number"
                        maxlength="11"
                        class="el-autocomplete"
                        @keyup.native.enter="handleEnter($event)"
                    />
                    <!-- <el-autocomplete
                        v-model="ruleForm.phone"
                        :fetch-suggestions="querySearchAsync"
                        placeholder="请输入手机号"
                        @select="handleSelect"
                        class="el-autocomplete"
                        size="small"
                        @keyup.native.enter="handleEnter($event)"
                    /> -->
                </el-form-item>
                <el-tag
                    v-for="(tag,index) in dynamicTags"
                    :key="index"
                    closable
                    :disable-transitions="false"
                    @close="handleClose(tag)"
                >
                    {{ tag.true_name }}-{{ tag.$stuagentLogic }}--{{ tag.phone }}
                </el-tag>
            </el-form>
            <span
                slot="footer"
                class="dialog-footer"
            >
                <el-button
                    type="primary"
                    size="small"
                    @click="fnSubmitFp()">确 定</el-button>
            </span>
        </el-dialog>
        <!-- /分配弹窗 -->

        <!-- /分页 -->
        <div class="pagination-wrapper clearfix">
            <el-checkbox
                v-model="checkedAll"
                :indeterminate="checkIndeterminate"
                @change="fnChangeChecked"
            >全选</el-checkbox>
            <el-button
                type="text"
                @click="fnDistribution()"
                :disabled="multipleSelection.length == 0 ? true : false"
            >分配</el-button>
            <el-button
                type="text"
                @click="fnDeleteFans()"
                :disabled="multipleSelection.length == 0 ? true : false"
            >删除</el-button>
            <el-pagination
                background
                layout="total, prev, pager, next"
                :current-page.sync="page.now_page"
                :total="page.total_count"
                :page-size="page.page_size"
                @current-change="getTableData"
            />
        </div>
    </div>
</template>

<script>
import { setDate } from '@/assets/js/utils';
export default {
    /**
     * @param  {Array}     tableData            //表单数据源
     * @param  {Object}    page                 //分页
     * @param  {String}    telFans              //粉丝姓名或手机号
     * @param  {String}    tel                  //管培生姓名或手机号
     * @param  {String}    stuagent             //上级管培生
     * @param  {Array}     date                 //选择时间
     * @param  {Number}    purchase             //考核结果
     * @param  {Array}     purchaseList         //考核结果数据
     * @param  {Boolean}   checkedAll           //全选状态
     * @param  {Array}     multipleSelection    //全选数据
     * @param  {Boolean}   checkIndeterminate   //全选状态
     * @param  {Array}     tableDataReord       //购买记录数据
     * @param  {Boolean}   DialogVisibleList    //购买记录数据弹窗
     * @param  {Boolean}   dialogVisibleFp      //分配弹窗开关
     * @param  {Object}    ruleForm             //分配弹窗字段
     * @param  {Array}     dynamicTags          //搜索管培生数据
     * @param  {Array}     restaurants          //管培生数据
     * @param  {Array}     schoolList           //学校数据列表
     * @param  {String}    prevHead             //记录掌大精英筛选数据
     * @param  {String}    prevPage             //记录掌大精英页码
     */
    data () {
        return {
            prevHead: '',
            prevPage: '',
            schoolList: [],
            dynamicTags: [],
            restaurants: [],
            ruleForm: {
                phone: ''
            },
            dialogVisibleFp: false,
            DialogVisibleList: false,
            tableDataReord: [],
            checkIndeterminate: false,
            multipleSelection: [],
            checkedAll: false,
            header: {
                date: [],
                tel: '',
                keyword_pre_stuagent_student_id: '',
                keyword_student_id: '',
                stuagent: '',
                telFans: '',
                purchase: 0,
                school_id: '',
                purchaseList: [{
                    value: 0,
                    label: '全部'
                },{
                    value: 1,
                    label: '是'
                },{
                    value: -1,
                    label: '否'
                }]
            },
            page: {
                now_page: 1,
                total_count: 0,
                page_size: 0
            },
            tableData: [],
            authResult: {}
        };
    },
    filters: {
        setPrice (val) {
            return val.toFixed(2);
        },
        setAimtype (val) {
            if (val == 1) {
                return '自营商品订单';
            } else if (val == 2) {
                return '自营店铺';
            } else if (val == 3) {
                return '非自营店铺';
            }
        },
        setStatus (val) {
            if (val == 0) {
                return '已付款';
            } else if (val == 1) {
                return '返利待入账';
            } else if (val == 2) {
                return '返利已入账';
            } else if (val == 3) {
                return '已退款';
            }
        }
    },
    watch: {
        DialogVisibleList (val) {
            if (!val) {
                this.tableDataReord = [];
            }
        },
        dialogVisibleFp (val) {
            if (!val) {
                this.dynamicTags = [];
            }
        }
    },
    created () {
        this.authResult = this.$route.meta.authResult;
        this.getParam();
        this.setHeader();
        this.getTableData();
        this.getSchoolName();
    },
    mounted () {
        if (window.history && window.history.pushState && this.prevPage !== '') {
            history.pushState(null, null, document.URL);
            window.addEventListener('popstate', this.goBack, false);
        }
    },
    destroyed(){
        if (this.prevPage !== '') {
            window.removeEventListener('popstate', this.goBack, false);
        }
    },
    methods: {
        /**
         * 设置表单header
         */
        setHeader () {
            this.$store.commit('SET_HEADER', [{
                title: "APP后台",
            },
            {
                title: '掌大精英'
            },
            {
                title: "分配粉丝"
            }]
            );
        },

        /**
         * 获取url参数
         */
        getParam () {
            let query = this.$route.query;

            if (query.phone !== undefined || query.num !== undefined || query.page !== undefined || query.header !== undefined) {
                this.header.tel = query.phone;
                this.header.purchase = query.num;
                this.prevPage = query.page;
                this.prevHead = query.header;
            }
        },

        /**
         * 监听返回事件
         */
        goBack () {
            console.log('1');
            if (this.prevPage !== '') {
                this.$router.replace({
                    name: 'studentAdministration',
                    query: {
                        page: this.prevPage,
                        header: this.prevHead
                    }
                });
            }
        },

        /**
         * 获取学校+城市
         */
        getSchoolName () {
            this.$post('/student/region_college%5Ccity_college_linkage', {},resp=>{
                if (resp.code == 1 && resp.data.length > 0) {
                    let list = [];

                    resp.data.map((item,index)=>{
                        list.push({
                            value: item.id,
                            label: item.name,
                            children: []
                        });
                        item.children.map(itm=>{
                            list[index].children.push({
                                value: itm.id,
                                label: itm.name
                            });
                        });
                        return false;
                    });
                    this.schoolList = list;
                } else if (resp.code == 0) {
                    this.$message({
                        type: 'waring',
                        message: resp.msg
                    });
                }
            });
        },

        /**
         * 获取表格数据
         */
        getTableData (page) {
            this.$post('/student/stuagent_fans%5Cget_fans_list', {
                page_id: page || this.page.now_page,
                agent_no: '',
                school_id: this.header.school_id !== '' ? this.header.school_id[1] : '',
                pre_stuagent_keyword: this.header.tel,
                fans_keyword: this.header.telFans,
                is_buy: this.header.purchase,
                // start_time: this.header.date.length !== 0 ? setDate(this.header.date[0]) : '',
                // end_time: this.header.date.length !== 0 ? setDate(this.header.date[1]) : '',
                keyword_pre_stuagent_student_id: this.header.keyword_pre_stuagent_student_id,
                keyword_student_id: this.header.keyword_student_id
            }, resp => {
                if (resp.code == 1) {
                    this.tableData = resp.data.list;
                    this.page.now_page = resp.data.page.now_page;
                    this.page.total_count = resp.data.page.total_count;
                    this.page.page_size = resp.data.page.page_size;
                }
            });
        },

        /**
         * 重置
         */
        fnFormReset () {
            this.header.school_id = this.header.tel = this.header.telFans = this.header.date = '';
            this.$set(this.header, 'purchase', 0);
            this.getTableData();
        },

        /**
         * 查看购买记录
         */
        fnGetbuyList (row) {
            this.$post('/student/stuagent_fans%5Cget_buy_list',{
                student_no: row.student_no
            },resp=>{
                if (resp.code == 1) {
                    this.tableDataReord = this.tableDataReord.concat(resp.data.list);
                    this.DialogVisibleList = !this.DialogVisibleList;
                } else if (resp.code == 0) {
                    this.$message({
                        type: 'warning',
                        message: resp.msg
                    });
                }
            });
        },

        /**
         * 跳转订单列表
         */
        fnJumpShop (row) {
            this.$router.replace({
                name: 'OrderList',
                query: {
                    aim_no: row.aim_no,
                    fans_fp: 1
                }
            });
        },

        /**
         * 分配
         */
        fnDistribution () {
            this.dialogVisibleFp = !this.dialogVisibleFp;
        },

        /**
         * 删除粉丝
         */
        fnDeleteFans () {
            let student = '';

            this.multipleSelection.map(item=>{
                student += item.student_no + ',';
            });

            this.$confirm('此操作将批量删除选中粉丝, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.$post('/student/stuagent%5Cdelete_fans',{
                    student_no: student
                },resp=>{
                    if (resp.code == 1) {
                        this.$message({
                            type: 'success',
                            message: '删除成功',
                            center: true
                        });
                        this.getTableData();
                    } else {
                        this.$message({
                            type: 'waring',
                            message: resp.msg,
                            center: true
                        });
                    }
                });
            });

        },

        /**
         * 选择管培生手机号
         */
        // querySearchAsync (queryString, cb) {
        //     var restaurants = this.restaurants;
        //     var results = queryString ? restaurants.filter(this.createStateFilter(queryString)) : restaurants;

        //     clearTimeout(this.timeout);
        //     this.timeout = setTimeout(() => {
        //         cb(results);
        //     }, 500 * Math.random());
        // },
        // createStateFilter (queryString) {
        //     return (state) => {
        //         return (state.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0);
        //     };
        // },
        // handleSelect (item) {
        //     if (this.dynamicTags.length == 1) {
        //         this.$message({
        //             type: 'warning',
        //             message: '最多可添加一个'
        //         });
        //         return;
        //     }

        //     console.log(item, 'item');

        //     this.$post('',{
        //         phone: ''
        //     }, resp=> {
        //         if (resp.code == 1) {
        //             this.dynamicTags = this.dynamicTags.concat(resp.data.list);
        //             this.ruleForm.phone = '';
        //         } else if (resp.code == 0) {
        //             this.$message({
        //                 type: 'warning',
        //                 message: resp.msg
        //             });
        //         }
        //     });
        // },

        /**
         * 搜索管培生
         */
        handleEnter () {
            let arr = [];

            if (this.dynamicTags.length == 1) {
                this.$message({
                    type: 'warning',
                    message: '最多可添加一个'
                });
                return;
            }

            if (this.ruleForm.phone.length !== 11) {
                this.$message({
                    type: 'warning',
                    message: '请输入正确的手机号'
                });
                this.ruleForm.phone = '';
                return;
            }

            this.$post('/student/stuagent%5Cget_by_phone',{
                phone: this.ruleForm.phone
            }, resp=> {
                if (resp.code == 1) {
                    arr.push(resp.data);
                    this.dynamicTags = this.dynamicTags.concat(arr);
                    console.log(this.dynamicTags, '11');
                    this.ruleForm.phone = '';
                } else if (resp.code == 0) {
                    this.$message({
                        type: 'warning',
                        message: resp.msg
                    });
                }
            });
        },

        /**
         * 确定分配
         */
        fnSubmitFp () {
            if (this.dynamicTags.length == 0) {
                this.$message({
                    type: 'warning',
                    message: '请选择要分配的管培生,不可以为空'
                });
                return;
            }


            let student = '';

            this.multipleSelection.map(item=>{
                student += item.student_no + ',';
            });

            this.$post('/student/stuagent%5Cset_agent_no',{
                student_no: student,
                agent_no: this.dynamicTags[0].agent_no
            },resp=>{
                if (resp.code == 1) {
                    this.$message({
                        type: 'success',
                        message: '分配成功'
                    });
                } else if (resp.code == 0) {
                    this.$message({
                        type: 'warning',
                        message: resp.msg
                    });
                }
            });

            this.dialogVisibleFp = !this.dialogVisibleFp;
            setTimeout(()=>{
                this.getTableData();
            },500);
        },

        /**
         * 移除手机号
         */
        handleClose (tag) {
            this.dynamicTags.splice(this.dynamicTags.indexOf(tag), 1);
        },

        /**
         * 选择Checkbox
         */
        fnSelect(selection) {
            if(selection.length == this.tableData.length) {
                this.checkedAll = true;
            }else{
                this.checkedAll = false;
            }
            if(selection.length > 0 && selection.length < this.tableData.length) {
                this.checkIndeterminate = true;
            }else{
                this.checkIndeterminate = false;
            }
        },
        fnSelectAllTop(selection) {
            if(selection.length > 0) {
                this.checkedAll = true;
            }else{
                this.checkedAll = false;
            }
            if(selection.length > 0 && selection.length < this.tableData.length) {
                this.checkIndeterminate = true;
            }else{
                this.checkIndeterminate = false;
            }
        },
        fnChangeChecked() {
            if(this.checkedAll){
                this.toggleSelection(1);
            }else{
                this.toggleSelection();
            }
        },
        toggleSelection(rows) {
            if (rows) {
                this.$refs.goodsTable.toggleAllSelection();
            } else {
                this.$refs.goodsTable.clearSelection();
            }
        },
        handleSelectionChange(val) {
            this.multipleSelection = val;
        },

        /**
         * 过滤函数
         */
        emptyFormatter(row, column, val) {
            if (!val) {
                return '--';
            }
            return val;
        }
    }
};
</script>

<style lang="less" scoped>
    .container {
        background-color: #fff;
        padding: 15px;
        display: flex;
        flex-direction: column;
        position: relative;
        width: 100%;
        .header {
            position: relative;
            display: flex;
            flex-wrap: wrap;
            align-items: center;
            .header-box {
                display: flex;
                margin-right: 20px;
                align-items: center;
                color: #606266;
                margin-bottom: 20px;
                .header-title {
                    margin-right: 10px;
                    white-space: nowrap;
                }
                .btn-import-wrap {
                    margin-left: 15px;
                    display: inline-block;
                    position: relative;
                    overflow: hidden;
                    cursor: pointer;
                    vertical-align: top;
                    .import-input {
                        margin-left: -100%;
                        position: absolute;
                        left: 0;
                        top: 0;
                        width: 200%;
                        height: 100%;
                        cursor: pointer;
                        opacity: 0;
                    }
                }
            }
            .header-right {
                display: flex;
                .el-button {
                    margin-left: 20px;
                }
            }
        }
        .curse-add {
            color: rgb(64, 158, 255);
            cursor: pointer;
        }
        .pagination-wrapper {
            padding-top: 10px;
            .el-pagination {
                float: right;
                padding: 0;
                background-color: transparent;
            }
        }
        .dialog-footer {
            display: flex;
            justify-content: center;
            align-items: center;
        }
    }
    .el-autocomplete {
        width: 350px;
    }
    .el-dialogAdd {
        transition: all 1s;
    }
    .el-tag {
        margin: 0 15px 15px 0;
    }
</style>
<style lang="less">
    .containerStudent .el-table__body-wrapper .el-table__body .el-table__row td {
        border-right: none;
    }
    .containerStudent .el-table__header-wrapper .el-table__header .has-gutter tr th {
        border-right: none;
    }
    .containerStudent .el-table .el-table_1_column_6  .cell {
        position: relative;
    }
    .containerStudent .el-range-editor--small .el-range-separator{
        padding: 0 1px !important;
    }
</style>